package com.js.statemachine.common;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author ：js
 * @date ：Created in 2021-03-17 11:47
 * @description: 业务统一返回结果
 * @version: 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BizUniformResult<T> {

    /**
     * 业务成功与否
     */
    private Boolean flag;
    /**
     * 描述信息
     */
    private String description;
    /**
     * 返回结果
     */
    private T data;


    public BizUniformResult(String description, T data) {
        if (this.checkDataExist(data)) {
            this.description = description;
            this.flag = true;
            this.data = data;
        } else {
            this.description = description;
            this.flag = false;
        }
    }

    public BizUniformResult(String description, boolean flag) {
        if (flag) {
            this.description = description + "成功";
        } else {
            this.description = description + "失败";
        }
        this.flag = flag;
    }


    private boolean checkDataExist(T data) {
        if (isNull(data)) {
            return false;
        } else if (List.class.isAssignableFrom(data.getClass()) && ((List) data).isEmpty()) {
            return false;
        } else {
            return !Map.class.isAssignableFrom(data.getClass()) || !((Map) data).isEmpty();
        }
    }

    public static boolean isNull(Object... objs) {
        for (Object obj : objs) {
            if (Objects.isNull(obj)) {
                return true;
            }
        }
        return false;
    }
}
